﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory.Xml;
using Spring.Data.Config;
using Gestion.Data.Dao;
using Gestion.Service.Business;
using Spring.Data.NHibernate;
using log4net.Config;

namespace Gestion.Config
{
    public class AppConfigurator
    {
        /// <summary>
        /// Obtiene la base de los archivos de configuración
        /// </summary>
        /// <returns></returns>
        private static String GetBasePath()
        {
            return System.Configuration.ConfigurationSettings.AppSettings["ConfigBasePath"];
        }

        private static String GetConfigPath()
        {
            return System.Configuration.ConfigurationSettings.AppSettings["ConfigPath"];
        }

        /// <summary>
        /// Configura Spring
        /// </summary>
        /// <returns></returns>
        public static IApplicationContext ConfigureApplicationContext()
        {
            String[] baseConfigFiles = System.IO.Directory.GetFiles(GetBasePath(), "ApplicationContext*.xml");
            //String[] baseConfigFiles = System.IO.Directory.GetFiles(GetBasePath(), "NewApplicationContext*.xml");

            String[] concreteConfigFiles = null;
            if (System.IO.Directory.Exists(GetConfigPath()))
                concreteConfigFiles = System.IO.Directory.GetFiles(GetConfigPath(), "ApplicationContext*.xml");
                //concreteConfigFiles = System.IO.Directory.GetFiles(GetConfigPath(), "NewApplicationContext*.xml");


            String[] configFiles;
            if (concreteConfigFiles == null)
                configFiles = baseConfigFiles;
            else
            {
                configFiles = new String[baseConfigFiles.Length + concreteConfigFiles.Length];

                int i = 0;
                foreach (String file in baseConfigFiles)
                {
                    configFiles[i] = file;
                    i++;
                }

                foreach (string file in concreteConfigFiles)
                {
                    configFiles[i] = file;
                    i++;
                }
            }


            NamespaceParserRegistry.RegisterParser(typeof(DatabaseNamespaceParser));
            XmlApplicationContext ac = new XmlApplicationContext(configFiles);

            return ac;
        }

        /// <summary>
        /// Configura Log4net
        /// </summary>
        public static void ConfigureLog4net()
        {
            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(GetBasePath() + "\\log4net.config"));
        }

    }
}
